import { fromJS } from 'immutable'

import { TRADE_DATA_QUERY_ACTION } from '../reducers/tradeDataQueryReducer'
import { getPosition, getCurrentOrder, getHistoryOrder, revokeOrder as revokeOrderReq } from '../../api/orderApi'
import { formatValue } from '../../utils/dataUtils'

export const TAB_TYPE_CURRENT_POSITION = 'current_position'
export const TAB_TYPE_CURRENT_ORDER = 'current_order'
export const TAB_TYPE_HISTORY_ORDER = 'history_order'
export const TAB_TYPE_ALL_POSITION = 'all_position'

/**
 * 设置数据查询类型
 * @param type
 * @returns {{data: {currentDataQueryType: *}, type: string}}
 */
export function setDataQueryType (type) {
  return {
    type: TRADE_DATA_QUERY_ACTION,
    data: {
      currentDataQueryType: type
    }
  }
}

let pollPositionEnabled = true

export function setPollPositionEnabled (enabled) {
  pollPositionEnabled = enabled
}

/**
 * 请求持仓
 * @param dispatch
 * @param isPoll
 */
function requestPosition (dispatch, isPoll) {
  getPosition().then(
    result => {
      dispatch({
        type: TRADE_DATA_QUERY_ACTION,
        data: {
          positionLoading: false,
          positionList: fromJS(result.data || [])
        }
      })
      setTimeout(() => {
        if (pollPositionEnabled && isPoll) {
          requestPosition(dispatch, isPoll)
        }
      }, 5000)
    }
  ).catch(_ => {
    setTimeout(() => {
      if (pollPositionEnabled && isPoll) {
        requestPosition(dispatch, isPoll)
      }
    }, 5000)
  })
}

/**
 * 轮询持仓
 * @returns {function(...[*]=)}
 */
export function pollPosition () {
  return (dispatch) => {
    setPollPositionEnabled(true)
    dispatch({
      type: TRADE_DATA_QUERY_ACTION,
      data: {
        positionLoading: true
      }
    })
    requestPosition(dispatch, true)
  }
}

/**
 * 查询持仓
 * @returns {function(...[*]=)}
 */
export function queryPosition () {
  return (dispatch) => {
    dispatch({
      type: TRADE_DATA_QUERY_ACTION,
      data: {
        positionLoading: true
      }
    })
    requestPosition(dispatch)
  }
}

let pollCurrentOrderEnabled = true

export function setCurrentOrderEnabled (enabled) {
  pollCurrentOrderEnabled = enabled
}

/**
 * 检查当前委托请求参数
 * @param getState
 * @param currentContract
 * @param pageIndex
 * @returns {boolean}
 */
function checkCurrentOrderRequestParams (getState, currentContract, pageIndex) {
  const currentOrderCurrentPage = getState().trade.dataQuery.get('currentOrderCurrentPage')
  const contract = getState().trade.market.get('currentContract')
  return currentOrderCurrentPage === pageIndex && formatValue(contract, 'InstrumentID') === formatValue(currentContract, 'InstrumentID')
}

/**
 * 请求当前委托
 * @param dispatch
 * @param getState
 * @param currentContract
 * @param pageIndex
 * @param isPoll
 */
function requestCurrentOrder (dispatch, getState, currentContract, pageIndex, isPoll) {
  getCurrentOrder({ pageIndex, pageSize: 5 }).then(
    result => {
      if (checkCurrentOrderRequestParams(getState, currentContract, pageIndex)) {
        dispatch({
          type: TRADE_DATA_QUERY_ACTION,
          data: {
            currentOrderLoading: false,
            currentOrderList: fromJS(result.data || []),
            currentOrderCurrentPage: result.current_page,
            currentOrderTotalPage: result.total_page
          }
        })
        setTimeout(() => {
          if (pollCurrentOrderEnabled && isPoll) {
            requestCurrentOrder(dispatch, getState, currentContract, pageIndex, isPoll)
          }
        }, 5000)
      }
    }
  ).catch(_ => {
    if (checkCurrentOrderRequestParams(getState, currentContract, pageIndex)) {
      setTimeout(() => {
        if (pollCurrentOrderEnabled && isPoll) {
          requestCurrentOrder(dispatch, getState, currentContract, pageIndex, isPoll)
        }
      }, 5000)
    }
  })
}

/**
 * 轮询当前委托
 * @param currentContract
 * @param pageIndex
 * @returns {function(...[*]=)}
 */
export function pollCurrentOrder (currentContract, pageIndex) {
  return (dispatch, getState) => {
    if (currentContract) {
      setCurrentOrderEnabled(true)
      dispatch({
        type: TRADE_DATA_QUERY_ACTION,
        data: {
          currentOrderLoading: true,
          currentOrderCurrentPage: pageIndex,
          currentOrderList: fromJS([])
        }
      })
      requestCurrentOrder(dispatch, getState, currentContract, pageIndex, true)
    }
  }
}

/**
 * 查询当前委托
 * @param currentContract
 * @param pageIndex
 * @returns {function(...[*]=)}
 */
export function queryCurrentOrder (currentContract, pageIndex) {
  return (dispatch, getState) => {
    if (currentContract) {
      dispatch({
        type: TRADE_DATA_QUERY_ACTION,
        data: {
          currentOrderLoading: true,
          currentOrderCurrentPage: pageIndex
        }
      })
      requestCurrentOrder(dispatch, getState, currentContract, pageIndex)
    }
  }
}

let pollHistoryOrderEnabled = true

export function setHistoryOrderEnabled (enabled) {
  pollHistoryOrderEnabled = enabled
}

/**
 * 检查历史委托请求参数
 * @param getState
 * @param currentContract
 * @param pageIndex
 * @returns {boolean}
 */
function checkHistoryOrderRequestParams (getState, currentContract, pageIndex) {
  const historyOrderCurrentPage = getState().trade.dataQuery.get('historyOrderCurrentPage')
  const contract = getState().trade.market.get('currentContract')
  return historyOrderCurrentPage === pageIndex && formatValue(contract, 'InstrumentID') === formatValue(currentContract, 'InstrumentID')
}

/**
 * 请求历史委托
 * @param dispatch
 * @param getState
 * @param currentContract
 * @param pageIndex
 * @param isPoll
 */
function requestHistoryOrder (dispatch, getState, currentContract, pageIndex, isPoll) {
  getHistoryOrder({ pageIndex, pageSize: 5 }).then(
    result => {
      if (checkHistoryOrderRequestParams(getState, currentContract, pageIndex)) {
        dispatch({
          type: TRADE_DATA_QUERY_ACTION,
          data: {
            historyOrderLoading: false,
            historyOrderList: fromJS(result.data || []),
            historyOrderCurrentPage: result.current_page,
            historyOrderTotalPage: result.total_page
          }
        })
        setTimeout(() => {
          if (pollHistoryOrderEnabled && isPoll) {
            requestHistoryOrder(dispatch, getState, currentContract, pageIndex, isPoll)
          }
        }, 5000)
      }
    }
  ).catch(_ => {
    if (checkHistoryOrderRequestParams(getState, currentContract, pageIndex)) {
      setTimeout(() => {
        if (pollHistoryOrderEnabled && isPoll) {
          requestHistoryOrder(dispatch, getState, currentContract, pageIndex, isPoll)
        }
      }, 5000)
    }
  })
}

/**
 * 轮询历史委托
 * @param currentContract
 * @param pageIndex
 * @returns {function(...[*]=)}
 */
export function pollHistoryOrder (currentContract, pageIndex) {
  return (dispatch, getState) => {
    if (currentContract) {
      setHistoryOrderEnabled(true)
      dispatch({
        type: TRADE_DATA_QUERY_ACTION,
        data: {
          historyOrderLoading: true,
          historyOrderCurrentPage: pageIndex,
          historyOrderList: fromJS([])
        }
      })
      requestHistoryOrder(dispatch, getState, currentContract, pageIndex, true)
    }
  }
}

/**
 * 撤单
 * @param order
 * @param success
 * @returns {function(...[*]=)}
 */
export function revokeOrder (order, success) {
  const params = {
    OrderSysID: order.get('OrderSysID'),
    ActionFlag: '1'
  }
  return dispatch => {
    revokeOrderReq(params).then(
      result => {
        if (success) {
          success()
        }
      }
    ).catch(_ => {
    })
  }
}
